import { VercelRequest, VercelResponse } from "@vercel/node";
import { saveTableRecords, FeiShuTable, getTableRecords, updateTableRecords } from "../feishu/bitable";
import { Activity } from "../entity/activity";
import { buildURLData } from 'web-utility';
import { QueryCriteria } from "../entity/base";

export default async function handler(req: VercelRequest, res: VercelResponse) {
    if (req.method == "GET") {
        const query = {};
        const approve = req.query.approve;
        if (approve) {
            query["filter"] = `${approve == QueryCriteria.YES ?
                'CurrentValue.[approve]="是"' :
                approve == QueryCriteria.NO ?
                    'CurrentValue.[approve]="否"' :
                    ""}
                `
        }
        const id = req.query.id || '';
        let urlParam = buildURLData(query);
        const data = await getTableRecords(FeiShuTable.Activity, `${urlParam}`, `${id}`)
        return res.status(200).json({
            message: 'query success',
            data
        });
    }
    if (req.method == "POST") {
        const body: Activity = req.body;
        body.approve = '否';

        const data = await saveTableRecords(FeiShuTable.Activity, body)
        return res.status(201).json({
            message: 'created success', data
        });
    }
    if (req.method == "PUT") {
        const recordId = req.query.recordId;

        if (!recordId) return res.status(400).json(
            { messsage: "recordId is not empty" }
        ).end();

        const body: Activity = req.body;
        body.approve = '是';

        await updateTableRecords(FeiShuTable.Activity, body, `${recordId}`);
        return res.status(200).json({
            message: 'modified success',
        });
    }

    return res.status(200).json({
        message: 'executed success',
    });
}